package io.bhex.sdk.config.domain;

import android.text.TextUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.bhex.baselib.network.Utils.CookieUtils;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.JsonConvertor;
import io.bhex.sdk.BhexSdk;
import io.bhex.sdk.UrlsConfig;
import io.bhex.sdk.config.bean.BackupDomainBean;
import io.bhex.sdk.config.bean.BackupDomainList;
import io.bhex.sdk.data_manager.MMKVManager;

/**
 * ================================================
 * 作   者：ppzhao
 * 创建时间：2020-04-26
 * 邮   箱：
 * 描   述：
 * ================================================
 */

public class BackupDomainManager {

    private static BackupDomainManager instance;
    private static BackupDomainBean currentDomain;
    private int currentDomainIndex;
    private BackupDomainBean h5Domain;

    public static BackupDomainManager getInstance(){
        if (instance == null) {
            instance = new BackupDomainManager();
        }
        return instance;
    }

    public BackupDomainManager() {
        hostCountMap = new HashMap<String, Integer>();
        setCurrentDoamin(0);    //TODO 默认第一个为主用域名
    }

    private void setCurrentDoamin(int index) {

        List<BackupDomainBean> backupDomainList = getBackupDomainList();
        if (backupDomainList != null && backupDomainList.size()>0) {
            if(index < backupDomainList.size()){
                currentDomainIndex = index;
                currentDomain = backupDomainList.get(index);
            }else{
                currentDomainIndex = 0;
                currentDomain = backupDomainList.get(0);
            }

            if (currentDomain.getLevel() == 1) {
                //如果当前域名是level =1 就用当前的
                h5Domain = currentDomain;
            }else{
                /** 设置H5域名 H5默认用第一个一级域名 ***/
                for (BackupDomainBean domain : backupDomainList) {
                    if (domain != null) {
                        if (domain.getLevel() == 1) {
                            h5Domain = domain;
                            break;
                        }
                    }
                }
            }

        }
    }

    /**
     * 保存或者更新备用域名
     * @param backupDomains
     */
    public void firstLoadBackupDomainList(BackupDomainList backupDomains) {
        List<BackupDomainBean> cacheBackupDomainList = getBackupDomainList();
        if (cacheBackupDomainList != null && cacheBackupDomainList.size()>0) {
            setCookie(cacheBackupDomainList);   //设置cookie
            //如果有缓存直接使用缓存,不再使用工程默认配置的域名列表
            return;
        }

        //首次加载 无本cache地缓存域名列表,把工程配置的域名列表保存进缓存
        saveBackupDomainList(backupDomains);

        setCurrentDoamin(0);    //TODO 首次加载 默认第一个为主用域名
    }

    /**
     * 保存或者更新备用域名
     * @param backupDomains
     */
    public void saveBackupDomainList(BackupDomainList backupDomains) {
        if (backupDomains != null) {
            setCookie(backupDomains);   //设置cookie

            String backupdomainJson = JsonConvertor.getInstance().toJson(backupDomains);
            if (!TextUtils.isEmpty(backupdomainJson)) {
                saveBackupDomainList(backupdomainJson);
            }
        }
    }

    /**
     * 保存或者更新备用域名
     * @param backupDomainListJson
     */
    private void saveBackupDomainList(String backupDomainListJson) {
        MMKVManager.getInstance().saveBackupDomainList(backupDomainListJson);   //加载到缓存
        DebugLog.e("DOMAIN-test","save domains "+backupDomainListJson);
    }

    /**
     * 备用域名列表
     * @return
     */
    public List<BackupDomainBean> getBackupDomainList() {
        String backupDomainListJson = MMKVManager.getInstance().getBackupDomainList();
        if (!TextUtils.isEmpty(backupDomainListJson)) {
            BackupDomainList backupDomains = JsonConvertor.getInstance().fromJson(backupDomainListJson, BackupDomainList.class);
            if (backupDomains != null) {
                ArrayList<BackupDomainBean> backupDomainList = new ArrayList<>();
                List<BackupDomainBean> normalList = backupDomains.getNormal();
                if (normalList != null) {
                    backupDomainList.addAll(normalList);
                }

                return backupDomainList;

            }
        }
        return null;
    }

    /**
     * 当前域名
     * @return
     */
    public BackupDomainBean getCurrentDomain() {
        return currentDomain;
    }

    /**
     * H5域名    注意：H5默认使用第一个 一级域名
     * @return
     */
    public BackupDomainBean getH5Domain() {
        return h5Domain;
    }

    /**
     * 切换域名
     */
    public void switchDomain(){
        List<BackupDomainBean> backupDomainList = getBackupDomainList();
        if (backupDomainList != null && backupDomainList.size()>0) {
            int nextDomainIndex = currentDomainIndex + 1;
            if(nextDomainIndex < backupDomainList.size()){
                //切换下一个域名
                setCurrentDoamin(nextDomainIndex);
            }else{
                //从头切换
                setCurrentDoamin(0);
            }
            UrlsConfig.switchDomain();
        }
    }


    private static HashMap<String, Integer> hostCountMap;


    public void countHostFailed(String host) {
//        host = convertHost(host);
        int hostFailedCount = getHostFailedCount(host);
        hostFailedCount++;
        hostCountMap.put(host, hostFailedCount);
    }

    public void clearCountHostFailed(String host) {
        hostCountMap.put(host,0);
    }

    public void clearAllCountHostFailed() {
        if (hostCountMap != null) {
            for (String key : hostCountMap.keySet()) {
                hostCountMap.put(key,0);
            }
        }
    }

    public int getHostFailedCount(String host) {
        if (TextUtils.isEmpty(host)) {
            return 0;
        }
        if (hostCountMap == null) {
            return 0;
        }
        if (hostCountMap.containsKey(host)) {
            return hostCountMap.get(host);
        } else {
            return 0;
        }
    }

    public void setCookie(BackupDomainList backupDomains) {
        if (backupDomains != null) {
            ArrayList<BackupDomainBean> backupDomainList = new ArrayList<>();
            List<BackupDomainBean> normalList = backupDomains.getNormal();
            if (normalList != null) {
                backupDomainList.addAll(normalList);
            }
            setCookie(backupDomainList);
        }
    }

    public void setCookie(List<BackupDomainBean> backupDomains) {
        if (backupDomains != null) {
            DebugLog.e("COOKIE-0-backup",backupDomains.toString());
            CookieUtils.setDomainsCookies(BhexSdk.getContext(),backupDomains);
        }
    }
//
//    public void setCookie(String domain) {
//        if (!TextUtils.isEmpty(domain)) {
//            CookieUtils.setCookies(BhexSdk.getContext(),domain);
//
//        }
//    }

    public boolean isInOurDomains(String domain){
        if (domain.startsWith("app.")) {
            domain = domain.replaceFirst("app.","");
        }else if(domain.startsWith("otc.")){
            domain = domain.replaceFirst("otc.","");
        }else if(domain.startsWith("ws.")){
            domain = domain.replaceFirst("ws.","");
        }else if(domain.startsWith("www.")){
            domain = domain.replaceFirst("www.","");
        }
        boolean isOurDomain = false;
        List<BackupDomainBean> backupDomainList = getBackupDomainList();
        if (backupDomainList != null && backupDomainList.size()>0) {
            for (BackupDomainBean backupDomainBean : backupDomainList) {
                String backupDomain = backupDomainBean.getDomain();
                if (!TextUtils.isEmpty(backupDomain) && domain.equals(backupDomain)) {
                    isOurDomain = true;
                    break;
                }
            }
        }

        return isOurDomain;

    }

    public boolean isOwnCurrentDomains(String domain){
        if (domain.startsWith("app.")) {
            domain = domain.replaceFirst("app.","");
        }else if(domain.startsWith("otc.")){
            domain = domain.replaceFirst("otc.","");
        }else if(domain.startsWith("ws.")){
            domain = domain.replaceFirst("ws.","");
        }
        boolean isOurDomain = false;

        if (currentDomain != null) {
            String currentDomain = BackupDomainManager.currentDomain.getDomain();
            if (domain.equals(currentDomain)){
                isOurDomain = true;
            }
        }

        return isOurDomain;

    }

//    public boolean isInOurConfigDomains(String domain){
//        if (domain.startsWith("app.")) {
//            domain = domain.replaceFirst("app.","");
//        }else if(domain.startsWith("otc.")){
//            domain = domain.replaceFirst("otc.","");
//        }else if(domain.startsWith("ws.")){
//            domain = domain.replaceFirst("ws.","");
//        }
//        boolean isOurDomain = false;
//        List<BackupDomainBean> backupDomainList = getBackupDomainList();
//        if (backupDomainList != null && backupDomainList.size()>0) {
//            for (BackupDomainBean backupDomainBean : backupDomainList) {
//                String backupDomain = backupDomainBean.getDomain();
//                if (!TextUtils.isEmpty(backupDomain) && domain.equals(backupDomain)) {
//                    isOurDomain = true;
//                    break;
//                }
//            }
//        }
//
//        return isOurDomain;
//    }


}
